package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"time"
	"wechatdev/model/mysql"

	"wechatdev/wechatdevrpc/internal/svc"
	"wechatdev/wechatdevrpc/wechatdevrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *wechatdevrpc.RegisterRequest) (*wechatdevrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	user := mysql.User{
		HeadImage: "https://ts1.tc.mm.bing.net/th/id/OIP-C.-rBqkricrrEXBZsFzjxtlQAAAA?rs=1&pid=ImgDetMain&o=7&rm=3",
		NickName:  in.NickName,
		Address:   in.Address,
		Mobile:    in.Mobile,
		Password:  in.Password,
		WxCode:    fmt.Sprintf("wx-%d%d", rand.Intn(100000), time.Now().Unix()),
	}
	err := user.FindUser(mysql.DB, in.Mobile)
	if err != nil {
		return nil, err
	}
	if user.ID != 0 {
		return nil, errors.New("用户已经存在")
	}
	err = user.RedisterUser(mysql.DB)
	if err != nil {
		return nil, errors.New("注册失败")
	}
	return &wechatdevrpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
